package models

type Goods struct {
	Id    int     `gorm:"auto_increment primary key" json:"id"`
	Name  string  `gorm:"type:varchar(25) not null" json:"name"`
	Price float64 `gorm:"type:decimal(10,2) not null" json:"price"`
	Img   string  `gorm:"type:varchar(255) not null" json:"img"`
	Intro string  `gorm:"type:varchar(25) not null" json:"intro"`
}

func Add(goods *Goods) error {
	tx := Db.Begin()
	err = Db.Create(goods).Error
	if err != nil {
		tx.Rollback()
		return err
	}
	if err = tx.Commit().Error; err != nil {
		return err
	}
	return nil
}
func List() ([]*Goods, error) {
	var goods []*Goods
	err = Db.Find(&goods).Error
	if err != nil {
		return nil, err
	} else {
		return goods, nil
	}
}
func Page(page, size int, name string, minPrice, maxPrice float64) ([]Goods, int64, error) {
	var goods []Goods
	var count int64
	query := Db.Model(&goods)
	err = query.Count(&count).Error
	if minPrice != 0 && maxPrice != 0 {
		query = query.Where("price between ? and ?", minPrice, maxPrice)
	}
	if name != "" {
		query = query.Where("name like ?", "%"+name+"%")
	}
	if err != nil {
		return nil, 0, err
	}
	err = query.Offset((page - 1) * size).Limit(size).Order("price desc").Find(&goods).Error
	if err != nil {
		return nil, 0, err
	}
	return goods, count, nil

}

func Del(id int) error {
	var goods *Goods
	err = Db.Where("id = ?", id).Delete(&goods).Error
	if err != nil {
		return nil
	} else {
		return nil
	}
}
